package com.zengqingfa.springboot.validation.demo.controller;

import com.zengqingfa.springboot.validation.demo.dto.Emp;
import com.zengqingfa.springboot.validation.demo.dto.EmpGroup;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/emp")
public class EmpController {

    @PostMapping("/createEmp")
    public String createEmp(@Valid @RequestBody Emp emp) {
        return "ok";
    }

    @PostMapping("/createEmp2")
    public String createEmp2(@Valid @RequestBody Emp emp, BindingResult result) {
        if (result.hasErrors()) {
            Map<String, String> map = new HashMap<>();
            // 获取校验结果，遍历获取捕获到的每个校验结果
            result.getFieldErrors().forEach(item ->{
                // 获取校验的信息
                String message = item.getDefaultMessage();
                String field = item.getField();
                // 存储得到的校验结果
                map.put(field, message);
            });
            return map.values().toString();
        }
        return "ok";
    }

    @PostMapping("/createEmp3")
    public String createEmp3(@Valid @RequestBody Emp emp) {
        return "ok";
    }

    @PostMapping("/addGroupValid")
    public String addGroupValid(@Validated({EmpGroup.AddGroup.class}) @RequestBody EmpGroup emp) {
        return "ok";
    }

    @PostMapping("/updateGroupValid")
    public String updateGroupValid(@Validated({EmpGroup.UpdateGroup.class}) @RequestBody EmpGroup emp) {
        return "ok";
    }





}